# -*- coding: utf-8 -*-
# created on 2017/01/17
from itertools import product
from sympy import Abs
from mathsolver.functions.hanshu.helper import ineq_equals, check_inter
from mathsolver.functions.base import BaseFunction, BaseValue, new_latex
from mathsolver.functions.hanshu.jiou_dingyi import jiou_dingyi, dairu_jiou


def jiou_budengshidairu(jiou, ineq):
    """奇偶性+等式 => 三个不等式
    :param jiou 奇/偶
    :param ineq sympy 不等式 Relational 类型"""
    eq, step = jiou_dingyi(jiou)
    operator = ineq.func
    left, right = ineq.args
    combinations = product((left, dairu_jiou(left, eq)), (right, dairu_jiou(right, eq)))
    ineqs = [operator(*ele).canonical for ele in combinations]
    return ineqs, step


class JiOuBiJiaoDaXiao(BaseFunction):
    """函数奇偶性比较大小"""

    def solver(self, *args):
        jiou, ineq, q_ineq = args
        ineq, q_ineq = ineq.sympify(), q_ineq.sympify()

        # 代入得不等式
        ineqs, st = jiou_budengshidairu(jiou, ineq)
        self.steps.append(["", st])

        # 判断是否包含
        res = False
        for item in ineqs:
            if ineq_equals(item, q_ineq):
                res = True
                self.steps.append(["", "所以 %s 成立" % new_latex(q_ineq)])
                break

        if not res:
            self.steps.append(["", "所以 %s 不成立" % new_latex(q_ineq)])

        self.label.add("函数奇偶性比较大小")
        self.output.append(BaseValue(res))
        return self


def dandiao_reverse(dandiao):
    dandiaos = {'增': '减', '减': '增'}
    return dandiaos[dandiao]


class OuHanShuDanDianBiJiao(BaseFunction):
    """偶函数与单调性比较大小"""

    def solver(self, *args):
        jiou, inter, dandiao, funcnames = args[0], check_inter(args[1]), args[2], args[3].get_value

        assert '偶' in jiou

        # 函数在 x 轴右端的单调性
        inter_min, inter_max = inter._inf, inter._sup
        if inter_min >= 0:
            pos_dandiao = dandiao
        elif inter_max <= 0:
            pos_dandiao = dandiao_reverse(dandiao)
        else:
            raise ValueError('do not know how to handle interval %s' % inter)
        self.steps.append(['', '由题意知 f(x) 在x轴右侧单调%s' % pos_dandiao])

        # 升序排列
        res = sorted(funcnames, key=lambda x: Abs(x.var), reverse=(pos_dandiao == '减'))
        self.steps.append(['', '根据偶函数的对称性可知：%s' % ' < '.join(funcname.printing() for funcname in res)])
        self.output.append(BaseValue(res))
        self.label.add('偶函数与单调性比较大小')
        return self


if __name__ == '__main__':
    pass
